package com.net.shard.config;

import com.net.shard.ShardDataSource;
import com.net.shard.ShardDataSourceConfigurer;
import com.net.shard.manager.ShardConfigManager;
import com.net.shard.manager.ShardSettingManager;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 *
 * @Description: <br>
 * @Project: hades <br>
 * @ Created in 2018/7/20 15:16 <br>
 */
@Order(2)
@Configuration
public class ShardDatabaseConfiguration {

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private ShardConfigManager shardConfigManager;

    @Autowired
    private ShardSettingManager shardSettingManager;

    @Value("${spring.datasource.shard.data-source-name}")
    String  dataSourceName;
    @Value("${spring.datasource.shard.min-pool-size}")
    Integer minPoolSize;
    @Value("${spring.datasource.shard.max-pool-size}")
    Integer maxPoolSize;
    @Value("${spring.datasource.shard.acquire-increment}")
    Integer acquireIncrement;
    @Value("${spring.datasource.shard.initial-pool-size}")
    Integer initialPoolSize;

    @Bean("shardDataSource")
    public DataSource shardDataSource() {
        ShardDataSource shardDatasource = new ShardDataSource();
        ShardDataSourceConfigurer shardDataSourceConfigurer = new ShardDataSourceConfigurer();
        shardDataSourceConfigurer.setShardConfigManager(shardConfigManager);
        shardDataSourceConfigurer.setShardSettingManager(shardSettingManager);
        shardDataSourceConfigurer.setDataSourceName(dataSourceName);
        shardDataSourceConfigurer.setMinPoolSize(minPoolSize);
        shardDataSourceConfigurer.setMaxPoolSize(maxPoolSize);
        shardDataSourceConfigurer.setAcquireIncrement(acquireIncrement);
        shardDataSourceConfigurer.setInitialPoolSize(initialPoolSize);
        shardDatasource.setShardDataSourceConfigurer(shardDataSourceConfigurer);
        return shardDatasource;
    }

    @Bean
    @Primary
    public SqlSessionFactoryBean shardSqlSessionFactory() {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        sqlSessionFactoryBean.setDataSource(shardDataSource());
        sqlSessionFactoryBean.setConfigLocation(resourceLoader.getResource("classpath:shard-mybatis.xml"));

        return sqlSessionFactoryBean;
    }

    @Bean
    @Primary
    public DataSourceTransactionManager ShardTransactionManager() {
        return new DataSourceTransactionManager(shardDataSource());
    }
}
